<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON格式化工具 - 在线工具集合</title>
    <script type="text/javascript" src="../utils/toast.js"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
            min-height: 100vh;
            color: #fff;
            position: relative;
            overflow-x: hidden;
        }

        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle at 50% 50%, rgba(255,255,255,0.1) 0%, transparent 50%);
            pointer-events: none;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 40px 20px;
            position: relative;
            z-index: 1;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            background: linear-gradient(45deg, #00ff88, #00b4d8);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .header p {
            color: rgba(255, 255, 255, 0.8);
            font-size: 1.1em;
        }

        .editor-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .editor-section {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            padding: 20px;
            backdrop-filter: blur(10px);
        }

        .editor-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .editor-title {
            font-size: 1.2em;
            color: #00ff88;
            font-weight: 500;
        }

        .editor-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .action-btn {
            padding: 8px 15px;
            border: none;
            border-radius: 6px;
            background: rgba(255, 255, 255, 0.1);
            color: #fff;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.9em;
            flex-shrink: 0;
        }

        .action-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        .editor {
            width: 100%;
            height: 400px;
            background: rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            padding: 15px;
            font-family: 'Consolas', monospace;
            font-size: 14px;
            line-height: 1.5;
            color: #fff;
            resize: none;
            outline: none;
            overflow: auto;
        }

        .editor:focus {
            border-color: #00ff88;
            box-shadow: 0 0 10px rgba(0, 255, 136, 0.2);
        }

        .options-section {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            padding: 20px;
            margin-bottom: 20px;
            backdrop-filter: blur(10px);
        }

        .options-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .option-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .option-group label {
            color: rgba(255, 255, 255, 0.8);
            font-size: 0.9em;
        }

        .option-group input[type="number"] {
            width: 80px;
            padding: 5px;
            border: none;
            border-radius: 4px;
            background: rgba(255, 255, 255, 0.1);
            color: #fff;
            font-size: 0.9em;
        }

        .error-message {
            background: rgba(255, 0, 0, 0.1);
            border: 1px solid rgba(255, 0, 0, 0.3);
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            color: #ff4444;
            display: none;
        }

        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: #00ff88;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .back-link:hover {
            transform: translateX(-5px);
        }

        @media (max-width: 768px) {
            .container {
                padding: 20px 10px;
            }

            .header h1 {
                font-size: 2em;
            }

            .editor-container {
                grid-template-columns: 1fr;
            }

            .editor {
                height: 300px;
            }

            .action-btn {
                padding: 6px 12px;
                font-size: 0.8em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="../index.html" class="back-link">← 返回首页</a>
        
        <div class="header">
            <h1>JSON格式化工具</h1>
            <p>支持转义/去转义、格式化、压缩与验证</p>
        </div>

        <div class="options-section">
            <div class="options-grid">
                <div class="option-group">
                    <label>缩进空格数：</label>
                    <input type="number" id="indentSize" value="2" min="1" max="8">
                </div>
                <div class="option-group">
                    <label>
                        <input type="checkbox" id="sortKeys" checked>
                        按键名排序
                    </label>
                </div>
                <div class="option-group">
                    <label>
                        <input type="checkbox" id="showLineNumbers" checked>
                        显示行号
                    </label>
                </div>
            </div>
        </div>

        <div class="editor-container">
            <div class="editor-section">
                <div class="editor-header">
                    <div class="editor-title">输入JSON</div>
                    <div class="editor-actions">
                        <button class="action-btn" onclick="clearInput()">清空</button>
                        <button class="action-btn" onclick="escapeJSON()">转义</button>
                        <button class="action-btn" onclick="unescapeJSON()">去转义</button>
                        <button class="action-btn" onclick="formatJSON()">格式化</button>
                        <button class="action-btn" onclick="compressJSON()">压缩</button>
                    </div>
                </div>
                <textarea id="inputEditor" class="editor" placeholder="在此输入JSON数据..."></textarea>
            </div>

            <div class="editor-section">
                <div class="editor-header">
                    <div class="editor-title">处理结果</div>
                    <div class="editor-actions">
                        <button class="action-btn" onclick="copyOutput()">复制</button>
                        <button class="action-btn" onclick="downloadJSON()">下载</button>
                    </div>
                </div>
                <textarea id="outputEditor" class="editor" readonly></textarea>
            </div>
        </div>

        <div class="error-message" id="errorMessage"></div>
    </div>

    <script>
        // DOM元素
        const inputEditor = document.getElementById('inputEditor');
        const outputEditor = document.getElementById('outputEditor');
        const errorMessage = document.getElementById('errorMessage');
        const indentSize = document.getElementById('indentSize');
        const sortKeys = document.getElementById('sortKeys');
        const showLineNumbers = document.getElementById('showLineNumbers');

        // 核心功能函数
        function formatJSON() {
            try {
                const input = inputEditor.value.trim();
                let json;
                
                // 直接尝试解析原始输入
                try {
                    json = JSON.parse(input);
                } catch {
                    // 处理被双引号包裹的特殊情况
                    if (input.startsWith('"') && input.endsWith('"')) {
                        json = JSON.parse(input.slice(1, -1));
                    } else {
                        throw new Error('无效的JSON格式');
                    }
                }

                const formatted = JSON.stringify(
                    sortKeys.checked ? sortObjectKeys(json) : json, 
                    null, 
                    parseInt(indentSize.value)
                );
                
                outputEditor.value = formatted;
                errorMessage.style.display = 'none';
            } catch (error) {
                showError(error.message);
            }
        }

        function compressJSON() {
            try {
                let jsonString = preprocessInput(inputEditor.value);
                const json = JSON.parse(jsonString);
                outputEditor.value = JSON.stringify(json);
                errorMessage.style.display = 'none';
            } catch (error) {
                showError(error.message);
            }
        }

        function escapeJSON() {
            try {
                const input = inputEditor.value;
                const escaped = input
                    .replace(/\\/g, '\\\\')
                    .replace(/"/g, '\\"')
                    .replace(/\//g, '\\/')
                    .replace(/\n/g, '\\n')
                    .replace(/\r/g, '\\r')
                    .replace(/\t/g, '\\t');
                outputEditor.value = `"${escaped}"`;
                errorMessage.style.display = 'none';
            } catch (error) {
                showError(error.message);
            }
        }

        function unescapeJSON() {
            try {
                let input = inputEditor.value;
                // 移除首尾的双引号（如果存在）
                if (input.startsWith('"') && input.endsWith('"')) {
                    input = input.slice(1, -1);
                }
                const unescaped = input
                    .replace(/\\\\/g, '\\')
                    .replace(/\\"/g, '"')
                    .replace(/\\\//g, '/')
                    .replace(/\\n/g, '\n')
                    .replace(/\\r/g, '\r')
                    .replace(/\\t/g, '\t');
                outputEditor.value = unescaped;
                errorMessage.style.display = 'none';
            } catch (error) {
                showError(error.message);
            }
        }

        // 辅助函数
        function preprocessInput(input) {
            if (input.startsWith('"') && input.endsWith('"')) {
                try {
                    const parsed = JSON.parse(input);
                    // 如果是基本类型则保持原样（如 "123" 会保留为字符串）
                    if (typeof parsed !== 'object') return input; 
                    return parsed;
                } catch {
                    return input; // 保持原始字符串
                }
            }
            return input;
        }

        function sortObjectKeys(obj) {
            if (typeof obj !== 'object' || obj === null) return obj;
            if (Array.isArray(obj)) return obj.map(sortObjectKeys);
            
            return Object.keys(obj).sort().reduce((acc, key) => {
                acc[key] = sortObjectKeys(obj[key]);
                return acc;
            }, {});
        }

        function showError(message) {
            errorMessage.textContent = `错误：${message}`;
            errorMessage.style.display = 'block';
        }

        function clearInput() {
            inputEditor.value = '';
            outputEditor.value = '';
            errorMessage.style.display = 'none';
        }

        function copyOutput() {
            outputEditor.select();
            document.execCommand('copy');
            toast.success("已复制到剪贴板");
        }

        function downloadJSON() {
            const content = outputEditor.value;
            if (!content) return;

            const blob = new Blob([content], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `formatted-${Date.now()}.json`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        }

        // 自动格式化
        let timeout;
        inputEditor.addEventListener('input', () => {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                try {
                    if (inputEditor.value.trim()) {
                        formatJSON();
                    }
                } catch (error) {
                    // 忽略自动格式化错误
                }
            }, 500);
        });

        // 初始化示例
        const exampleJSON = {
            "name": "示例JSON",
            "description": "包含特殊字符的示例：\"引号\", \\反斜杠, /正斜杠",
            "specialChars": {
                "newline": "换行符\\n",
                "tab": "制表符\\t",
                "unicode": "Unicode示例：\\u4e2d\\u6587"
            }
        };
        inputEditor.value = JSON.stringify(exampleJSON, null, 2);
        formatJSON();
    </script>
</body>
</html>